// import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request <interceptor></interceptor>
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const { token } = store.getters
    if (token) {
      console.log(token)
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    console.log(response)
    const { data, status, msg, success } = response.data
    if (status === 200) {
      return data
    }
    if (!success) {
      return Message.error(msg)
    }
    // if (errno === 0) {
    //   return data
    // } else if (errno === 9997) {
    //   // 处理token失效
    //   store.dispatch('user/logout')
    //   router.push('/login')
    // } else {
    //   Message.error(errmsg)
    //   return Promise.reject(errmsg)
    // }
    return response.data.data
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
